package com.android.task5;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;



public class FlickrRESTResponse {
	
	private ArrayList<FlickrPhoto> photos;
	
	private SAXParserFactory factory ;
	private SAXParser parser;
	
	private DefaultHandler saxHandler = new MySAXHandler();
	
	private class MySAXHandler extends DefaultHandler{

	    public void startElement(String uri, String localName,
	        String qName, org.xml.sax.Attributes attributes)
	    throws SAXException {
	    	
	    	String farm;
   		  	String serverId;
   		  	String photoId;
   		  	String secret;
	    		
	    		farm = attributes.getValue("farm");
	    		serverId = attributes.getValue("server");
	    		photoId = attributes.getValue("id");
	    		secret = attributes.getValue("secret");
	    		if(farm != null && serverId!=null && photoId != null && secret != null){
	    		FlickrPhoto newPhotoUrl = new FlickrPhoto(farm, serverId, photoId, secret);
	    		photos.add(newPhotoUrl);
	    	  }
	    }
	};
	
	public FlickrRESTResponse(){
		photos = new ArrayList<FlickrPhoto>();
		try {
			factory = SAXParserFactory.newInstance();
			parser = factory.newSAXParser();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void parseRESTResponse(InputStream is){
		try {
			parser.parse(is, saxHandler);
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public ArrayList<FlickrPhoto> getFlickrPhotos(){
		return photos;
	}
	
	

}
